package com.lite.business.service.middletab.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lite.business.convert.middletab.MiddleTabConvert;
import com.lite.business.entity.commodities.ContractCommodity;
import com.lite.business.entity.middletab.MiddleTab;
import com.lite.business.exception.BusinessException;
import com.lite.business.mapper.commodities.CommoditiesMapper;
import com.lite.business.mapper.middletab.MiddleTabMapper;
import com.lite.business.service.middletab.MiddleTabService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author stranger
 * @since 2022-10-25
 */
@Service
public class MiddleTabServiceImpl extends ServiceImpl<MiddleTabMapper, MiddleTab> implements MiddleTabService {


    @Autowired
    MiddleTabMapper middletabMapper;

    @Autowired
    MiddleTabConvert middletabConvert;

    @Autowired
    CommoditiesMapper commoditiesMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "contractCommoditiesList", allEntries = true)
    public Boolean addContractCommodity(MiddleTab middleTab) throws BusinessException {
        int count = middletabMapper.insert(middleTab);
        if (count <= 0) {
            throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "新增合同商品失败");
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "contractCommoditiesList", allEntries = true)
    public Boolean removeContractCommodity(Integer middleTabId) throws BusinessException {
        int count = middletabMapper.delete(new LambdaQueryWrapper<MiddleTab>().eq(MiddleTab::getId, middleTabId));
        if (count <= 0) {
            throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除合同订购商品失败");
        }
        return true;
    }

    @Override
    @Cacheable(value = "contractCommoditiesList")
    public List<ContractCommodity> listContractCommodity(Integer page, Integer size, Integer contractId) throws BusinessException {
        List<ContractCommodity> contractCommodities = middletabMapper
                .selectAllCommoditiesByContractId(new Page<>(page, size), contractId).getRecords();
        if (Objects.isNull(contractCommodities)) {
            throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "获取合同订购商品列表信息失败");
        }
        return contractCommodities;
    }

}
